#include <linux/module.h>
#include <linux/init.h>
#include <linux/kthread.h>
#include <linux/delay.h>

static struct rw_semaphore rw_sem;
static int state_flags = 0;

static int writer_func(void *data)
{
    int i;

    for (i = 0; i < 5 && !state_flags; i++) {
        down_write(&rw_sem);
        printk(KERN_INFO "writer: writing...\n");
        msleep(5);
        up_write(&rw_sem);
    }

    return 0;
}

static int reader_func(void *data)
{
    int i;

    for (i = 0; i < 10 && !state_flags; i++) {
        down_read(&rw_sem);
        printk(KERN_INFO "reader: reading...\n");
        msleep(1);
        up_read(&rw_sem);
    }

    return 0;
}

static int __init rw_sem_init(void)
{
    struct task_struct *reader1, *reader2, *writer;

    init_rwsem(&rw_sem);

    reader1 = kthread_create(reader_func, NULL, "reader1");
    reader2 = kthread_create(reader_func, NULL, "reader2");
    writer = kthread_create(writer_func, NULL, "writer");

    return 0;
}

static void __exit rw_sem_exit(void)
{
	state_flags = 1;
    printk(KERN_INFO "RW semaphore module exit\n");
}

module_init(rw_sem_init);
module_exit(rw_sem_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
